<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Proitem extends Auth
{
    public function __construct(Request $request){
        $this->getChildIDdata = [];
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    // 配件
    public function list(Request $request)
    {   
        if(isset($this->data['request']) && $this->data['request'] == 'vue'){
            $returnData['item_cat'] = getSearch('pro_item_type','zu',['zu.*,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
            // dump($returnData['item_cat']);die;
            foreach ($returnData['item_cat'] as $k => $v) {
                if($v['is_public'] ==1){
                    $pro_name = getValue('multi_lang',['mkey'=>'pro_'.$v['pro_id'],'lang'=>$this->lang],'content');
                    $prochar_model = getValue('prochar',['id'=>$v['prochar_id']],'model');
                    $returnData['item_cat'][$k]['pro'] = $pro_name.($prochar_model ? ' / '.$prochar_model : '');
                }else{
                    $returnData['item_cat'][$k]['pro'] = '';
                }
                // $returnData['item_cat'][$k]['is_status'] = lang(getViewMultiLanguage($v['status']));
                $returnData['item_cat'][$k]['is_status'] = $v['status'] == 1 ? lang('normal') : lang(getViewMultiLanguage($v['status'],$this->lang));
                $returnData['item_cat'][$k]['is_public_note'] = $v['is_public'] == 1 ? 'o' : '-';
                $returnData['item_cat'][$k]['is_hide_note'] = $v['is_hide'] == 1 ? 'o' : '-';
            }
            
            $returnData['size'] = count( $returnData['item_cat']);
            // 获取分页数据
            if(isset($this->data['page']) && isset($this->data['limit'])){
                $returnData['item_cat'] = array_slice($returnData['item_cat'],$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                $returnData['page'] = $this->data['page'];
            }else{
                $returnData['page'] =1;
            }

            return json_encode($returnData);

        }else{
            return view('list',['request'=>'list']);
        }
        
    }

    public function addopen(){
        if(isset($this->data['request']) && $this->data['request'] == 'insert'){

            $noticeText = $this->noticeText_();
            if(!empty($noticeText)) return $noticeText;

            $has = hasData('multi_lang',['lang'=>$this->lang,'content'=>$this->data['itemcat_name'][$this->lang],'mkey'=>['like','%pro_item_type_%']]);
            if($has){
                return json_encode(array('status'=>3,'msg'=>' '.lang('already_exists')));
            }
            if($this->data['is_public'] == 'false'){
                $insertitem['is_public'] = 2;
            }else{
                $noticeText = noticeText($this->data,['pro_id'=>'配件产品','prochar_id'=>'配件角色']);
                if(!empty($noticeText)) return json_encode($noticeText);

                $insertitem['is_public'] = 1;
                $insertitem['pro_id'] = $this->data['pro_id'];
                $insertitem['prochar_id'] = $this->data['prochar_id'];
                
            }
            $insertitem['qty'] = $this->data['qty'];
            Db::startTrans();
            $res = insertData('pro_item_type',$insertitem);
            if($res){
                $res1 = updateData('pro_item_type',['id'=>$res],['mkey'=>'pro_item_type_'.$res]);

                $lang_cate = getLanguage();
                foreach ($lang_cate as $k => $v) {
                    $multi_langContent = $this->data['itemcat_name'][$v['code']] == '' ? $this->data['itemcat_name'][$this->lang] : $this->data['itemcat_name'][$v['code']];
                    $res2 = insertData('multi_lang',['mkey'=>'pro_item_type_'.$res,'lang'=>$v['code'],'content'=>$multi_langContent]);
                }
                if($res1 && $res2){
                    Db::commit();
                    return json_encode(array('status'=>1,'msg'=>$this->data['itemcat_name'][$this->lang].' '.lang('added_successfully')));
                }else{
                    Db::rollback();
                    return json_encode(array('status'=>0,'msg'=>$this->data['itemcat_name'][$this->lang].' '.lang('add_failed')));
                }
            }else{
                Db::rollback();
                return json_encode(array('status'=>0,'msg'=>$this->data['itemcat_name'][$this->lang].' '.lang('add_failed')));
            }

        }else if(isset($this->data['request']) && $this->data['request'] == 'add'){
            $procat = getMultiLangName('procat',['*'],['status'=>1],'drank asc');
            $procat = getTree($procat);
            return view('itemopen',['title'=>lang('add_accessory_type'),'request'=>'add','procat'=>$procat]);
        }else{
            return $this->proAddNewJump_itemAjax($this->data,$this->lang);
        }
    }


    public function getProcat()
    {
        $procat = getMultiLangName('procat',['*'],['status'=>1],'drank asc');
        $procat = getTree($procat);
        return json_encode($procat);
    }


    public function proAddNewJump_itemAjax($data,$lang){
        if($data['request'] == 'pro'){
            $pro2cate = getDatas('pro2cate',['*'],['procat_id'=>$data['cat_id']]);
            $prolist = [];
            if(!empty($pro2cate)){
                foreach ($pro2cate as $k => $v) {
                    if(isset($data['pro_id']) && $v['pro_id'] != $data['pro_id']){
                        $result = getMultiLangName('pro',['*'],['id'=>$v['pro_id']],'id asc');
                        if(!empty($result)) $prolist[] = $result[0];
                        
                    }
                    else{
                        $result = getMultiLangName('pro',['*'],['id'=>$v['pro_id']],'id asc');
                        if(!empty($result)) $prolist[] = $result[0];
                    }
                }
            }else{
                $prolist[0]  = ['id'=>0,'name_zh'=>lang('no_data'),'name_en'=>lang('no_data'),'name_pt'=>lang('no_data')];
            }
            // dump($prolist);die;
            return json_encode(array('status'=>1,'msg'=>'OK','data'=>$prolist));
        }elseif ($data['request'] == 'prochar') {
            $prochar = getDatas('prochar',['*'],['pro_id'=>$data['id']]);
            if(!empty($prochar)){
                foreach ($prochar as $k => $v) {
                    // $returnFeature[$k]['content_zh'] = $v['model'] == '' ? '' : '型号'.$v['model'].'/';
                    // $returnFeature[$k]['content_en'] = $v['model'] == '' ? '' : '型号'.$v['model'].'/';
                    // $returnFeature[$k]['content_pt'] = $v['model'] == '' ? '' : '型号'.$v['model'].'/';
                    $getLanguage = getLanguage($this->lang);
                    foreach ($getLanguage as $keygetLanguage => $valuegetLanguage) {
                        $returnFeatures['content_'.$valuegetLanguage['code']] = $v['model'] == '' ? '' : '型号'.$v['model'].'/';
                    }

                    $prochar2feature = getDatas('profeature2char',['*'],['prochar_id'=>$v['id']]);
                    if(!empty($prochar2feature)){
                        foreach ($prochar2feature as $k1 => $v1) {
                            $feature = getMultiLangName('proattr_value',['*'],['id'=>$v1['profeature_value_id']],'id asc')[0];
                            // $returnFeature[$k]['content_zh'] .= $feature['name_zh'] == '' ? '' : $feature['name_zh'].'/';
                            // $returnFeature[$k]['content_en'] .= $feature['name_en'] == '' ? '' : $feature['name_en'].'/';
                            // $returnFeature[$k]['content_pt'] .= $feature['name_pt'] == '' ? '' : $feature['name_pt'].'/';
                            foreach ($returnFeatures as $keyreturnFeature => $valuereturnFeature) {
                                $returnFeatures[$keyreturnFeature] = $valuereturnFeature . $feature['name_pt'] == '' ? '' : $feature['name_pt'].'/';
                            }
                        }
                    }
                    
                    foreach ($returnFeatures as $krtrim => $vrtrim) {    
                        rtrim($returnFeatures[$krtrim],'/');
                    }
                    $returnFeatures['id'] =  $v['id'];
                    $returnFeature[$k] = $returnFeatures;
                }
            }else{
                $returnFeature=[];
            }
            // dump($returnFeature);die;
            return json_encode(array('status'=>1,'msg'=>'OK','data'=>$returnFeature));

        }else if($data['request'] == 'searchText'){
            // return $this->data;
            if(isset($data['searchText']) && $data['searchText']){
                $join  = [['multi_lang mu','zu.mkey = mu.mkey']];
                $field = ['zu.*,mu.content'];
                $where['mu.lang'] = $lang;
                if(isset($data['pro_id'])){
                    $where['zu.id'] = ['not in',$data['pro_id']];
                }
                
                // 查找
                $where['zu.id|mu.content'] = ['like',"%".$data['searchText'].'%'];  
                $where['zu.is_item'] = 0;
                // $where['zu.is_public'] = 1;
                $productList = getSearch('pro','zu',$field,$where,$join,'zu.id desc');
                if(!empty($productList)){
                    foreach ($productList as $k => $v) {
                        // $productList[$k]['name_'.$v['lang']] = getValue('multi_lang',['mkey'=>'pro_'.$v['id'],'lang'=>$v['lang']],'content');
                        $pro_multi = getDatas('multi_lang',['*'],['mkey'=>'pro_'.$v['id']]);
                        foreach ($pro_multi as $k1 => $v1) {
                            $productList[$k]['name_'.$v1['lang']] = $v1['content'];
                        }
                    }
                    return json_encode(array('status'=>1,'msg'=>'OK','data'=>$productList));
                }else{
                    return json_encode(array('status'=>3,'msg'=>lang('no_data')));
                }
            }else{
                return json_encode(array('status'=>3,'msg'=>lang('no_data')));
            }
        }
    }

    function noticeText_()
    {
        if(isset($this->data['itemcat_name'])){
            foreach ($this->data['itemcat_name'] as $key => $value) {
                if(!$value){
                    return json_encode(array('status'=>2,'msg'=>'请填写 '.getNoticLang($key).' 名称'));
                    break;
                }
            }
        }
        $noticeText = noticeText($this->data,['qty'=>'请填写：数量'],'不能为空','isset');
        if(!empty($noticeText)) return json_encode($noticeText);
        
    }

    public function editopen(){
        if(isset($this->data['request']) && $this->data['request'] == 'update'){

            // dump($this->data);die;
            $noticeText = $this->noticeText_();
            if(!empty($noticeText)) return $noticeText;

            if($this->data['is_public'] == 'false'){
                $insertitem['is_public'] = 2;
            }else{
                // if(isset($this->data['pro_id']) && $this->data['pro_id'] && isset($this->data['prochar_id']) &&$this->data['prochar_id']){
                    $insertitem['is_public'] = 1;
                // }else{
                //     return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
                // }

                $noticeText = noticeText($this->data,['pro_id'=>'配件产品','prochar_id'=>'配件角色']);
                if(!empty($noticeText)) return json_encode($noticeText);
            }

            Db::startTrans();
                $insertitem['qty'] = $this->data['qty'];
                $insertitem['pro_id'] = $this->data['pro_id'];
                $insertitem['prochar_id'] = $this->data['prochar_id'];
                $res = updateData('pro_item_type',['id'=>$this->data['id']],$insertitem);
                foreach ($this->data['itemcat_name'] as $k => $v) {
                    $res2 = updateData('multi_lang',['mkey'=>'pro_item_type_'.$this->data['id'],'lang'=>$k],['content'=>$v]);
                    if($k == $this->lang) $content = $v;
                }
                if($res >= 0 && $res2 >= 0){
                    Db::commit();
                    return json_encode(array('status'=>1,'msg'=>$content.' '.lang('edited_successfully')));
                }else{
                    Db::rollback();
                    return json_encode(array('status'=>0,'msg'=>$content.' '.lang('edit_failed')));
                }
            
        }else if(isset($this->data['request']) && $this->data['request'] == 'edit'){

            return view('itemopen',['title'=>lang('edit_accessory_type'),'request'=>'edit','id'=>$this->data['id']]); 
            
        }else if(isset($this->data['request']) && $this->data['request'] == 'requestAjax'){
            // 产品分类
            $procat = getMultiLangName('procat',['*'],['status'=>1],'drank asc');
            $procat = getTree($procat);
            // 产品

            // 配件类型
            $item = getMultiLangName('pro_item_type',['*'],['id'=>$this->data['id']],'id asc')[0];
            if($item['is_public'] == 1){
                $itempro_ = getMultiLangName('multi_lang',['*'],['mkey'=>'pro_'.$item['pro_id']],'id asc');
                if(!empty($itempro_)){
                    $itempro = $itempro_[0];
                    $itempro['id'] = $item['pro_id']; 
                }else{
                    $itempro = [];
                }
                $itemprochar_ = getDatas('prochar',['id,model'],['id'=>$item['prochar_id']]);
                $getLanguage = getLanguage($this->lang);

                if($itemprochar_){
                    $itemprochar = $itemprochar_;
                    foreach ($getLanguage as $keygetLanguage => $valuegetLanguage) {
                        // $itemprochar['content_'.$valuegetLanguage['code']] = lang('model').'_'.$itemprochar['model'];
                        $itemprochar['content_'.$valuegetLanguage['code']] = isset($itemprochar['model']) ? lang('model').'_'.$itemprochar['model'] : '' ;
                    }    
                } else{
                    $itemprochar = [];
                }
                return json_encode(array('status'=>1,'data'=>['procat'=>$procat,'itempro'=>$itempro,'itemprochar'=>$itemprochar,'item'=>$item]));
            }else{
                // return view('itemopen',['title'=>lang('edit_accessory_type'),'id'=>$this->data['id'],'request'=>'edit','procat'=>$procat,'item'=>$item]);
                return json_encode(array('status'=>1,'data'=>['procat'=>$procat,'item'=>$item]));
            }
        }else {
            return $this->proAddNewJump_itemAjax($this->data,$this->lang);
        }
    }


    // 批量/单个删除
    public function batchDel()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->changeStatus($this->data,$this->lang);
        }
    }

    // 批量/单个隐藏
    public function batchHide()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->changeStatus($this->data,$this->lang);
        }
    }

    // 批量/单个恢复
    public function batchRestore()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->changeStatus($this->data,$this->lang);
        }
    }

    // 批量/单个清除
    public function batchClear()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->requestDel($this->data,$this->lang);
        }
    }


    public function changeStatus($data,$lang){
        if($data['id']){
            $res = updateData('pro_item_type',['id'=>$data['id']],['status'=>$data['status']]);
            $content = getValue('multi_lang',['mkey'=>'pro_item_type_'.$data['id'],'lang'=>$lang],'content');
            if($res){
                return json_encode(array('status'=>1,'msg'=>$content.' '.lang(getViewMultiLanguage($data['status'])).' '.lang('successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>$content.' '.lang(getViewMultiLanguage($data['status'])).' '.lang('failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
        }
    }

    public function requestDel($data,$lang){
        if($data['id']){
            $content = getValue('multi_lang',['mkey'=>'pro_item_type_'.$data['id'],'lang'=>$lang],'content');
            $res = deleteData('pro_item_type',['id'=>$data['id'],'status'=>2]);
            if($res){
                $res1 = deleteData('multi_lang',['mkey'=>'pro_item_type_'.$data['id']]);
                return json_encode(array('status'=>1,'msg'=>$content.' '.lang('cleared_successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>$content.' '.lang('clear_failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
        }
    }

}